package database;

/**
 * @Author: webmaster@pavel-kaminsky.com
 * @Date: 31/08/11
 */


import java.sql.*;

public class JavaDBExample {
    static Connection conn;

    public static void main(String[] args) throws Exception {

        if (args.length != 2) {
            System.out.println("Usage: <Name> <Address>");
            System.exit(1);
        }

        String dbName = "UsersDB";
        String connectionURL = "jdbc:derby:" + dbName + ";create=true";
        Class.forName("org.apache.derby.jdbc.EmbeddedDriver");
        conn = DriverManager.getConnection(connectionURL);

        // create table
        Statement stmt = conn.createStatement();
        stmt.executeUpdate("CREATE TABLE USERS (ID NUMBER NOT NULL, UserName VARCHAR(250) NOT NULL)");

        // insert user
        PreparedStatement psInsert = conn.prepareStatement("insert into USERS values (?,?)");
        psInsert.setInt(1, 1);
        psInsert.setString(2, "Lenny Kravitz");
        psInsert.executeUpdate();

        // load user
        Statement usetStmt = conn.createStatement();
        ResultSet rs = usetStmt.executeQuery("select * from USERS");

        while (rs.next()) {
            System.out.println("Id: " + rs.getInt(1) + " Name:" + rs.getString(2));
        }
        rs.close();
    }
}